<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select v-model="query.QueryType" placeholder="查询方式" class="handle-select mr10">
          <el-option key="1" label="用户名" value="username"></el-option>
          <el-option key="2" label="物资名" value="itemname"></el-option>
          <el-option key="3" label="归还状态" value="return_status"></el-option>
        </el-select>
        <div>
          <el-input v-model="query.SearchInput" placeholder="请输入" class="handle-input mr10"></el-input>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <el-table
          :data="tableData"
          height="550"
          border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="itemname" label="物资名" align="center"></el-table-column>
        <el-table-column prop="return_state" label="归还状态" align="center"></el-table-column>
        <el-table-column prop="borrow_time" label="出借时间" align="center"></el-table-column>
        <el-table-column prop="return_time" label="归还时间" align="center"></el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div v-if="HoverControl == scope.$index" @mouseleave="handleMouseLeave" class="temp">
              <el-button text @click="changeUser(scope.$index,scope.row)">
                更改用户
              </el-button>
              <el-button text @click="changeItem(scope.$index,scope.row)">
                更改物资
              </el-button>
            </div>
            <el-button v-else text :icon="Sort" @mouseover="handleMouseOver(scope.$index)">
              物资信息更改
            </el-button>
            <el-button v-if="IsShowBtn(scope.$index,scope.row)" text :icon="Edit" @click="handleReturnPost(scope.$index, scope.row)">
              提交归还申请
            </el-button>
            <el-button text :icon="Delete" class="red" @click="handleDelete(scope.$index, scope.row)">
              删除该条记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, watch} from 'vue';
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, Search, Sort} from '@element-plus/icons-vue';
import axios from "axios";
import {Plus} from "@element-plus/icons-vue/dist/index";


interface BrInfo {
  id: string;
  username: string;
  itemname: string;
  return_state: string;
  borrow_time: string;
  return_time: string;
  [key: string]: string;
}

const query = reactive({
  QueryType: 'username',
  SearchInput: '',
  pageIndex: 1,
  pageSize: 10
});

const HoverControl = ref(-1)
const allData = ref<BrInfo[]>([]);
const tableData = ref<BrInfo[]>([]);
const handleMouseOver = (index: number) => {
  HoverControl.value = index
}
const handleMouseLeave = () => {
  HoverControl.value = -1
}
// 获取表格数据
const getData = () => {
  // TODO 获取全部归还记录
  axios.get(`http://localhost:8080/infos`)
      .then(res=>{
        allData.value=res.data.data
        // console.log(allData.value)
        //   将归还状态置为 已归还/未归还
        for(let i=0;i<allData.value.length;i++){
          if(allData.value[i].return_state=="0"){
            allData.value[i].return_state="未归还"
            allData.value[i].return_time="——"
          }else{
            allData.value[i].return_state="已归还"
          }
        }
        tableData.value = allData.value
      })
};
getData();

// 查询操作
const handleSearch = () => {
  if(query.SearchInput==""){
    tableData.value=allData.value
  }else {
    tableData.value = []
    for(let i=0;i<allData.value.length;i++){
      if(allData.value[i][query.QueryType]!=null&&allData.value[i][query.QueryType].toLowerCase().indexOf(query.SearchInput.toLowerCase())!=-1){
        tableData.value.push(allData.value[i])
      }
    }
  }
};
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getData();
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
let form = reactive({
  name: '',
  address: ''
});


const IsShowBtn = (index: number, row: any) => {
  return row.return_state == "未归还";
}
const changeUser = (index: number, row: any) => {
  //TODO 更改用户请求
  ElMessageBox.confirm('确定要更改用户吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        if (row.return_state == "已归还") {
          ElMessage.error("该物资已归还，无法更改用户!")
          return
        }
        // 输入新的用户名
        ElMessageBox.prompt('请输入新的用户名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '用户名不能为空'
        }).then(({ value }) => {
          axios.put(`http://localhost:8080/returninfos`,{
            username:value,
            itemname:row.itemname,
            return_state:0,
            borrow_time:row.borrow_time,
            return_time:null
          })
              .then(res=>{
                if(res.data.status===0){
                  ElMessage.success("更改用户成功!")
                  getData()
                }else{
                  ElMessage.error("更改用户失败!")
                }
              })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消输入'
          });
        });
      })
};

const changeItem = (index: number, row: any) => {
  //TODO 更改物资请求
  ElMessageBox.confirm('确定要更改物资吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        if (row.return_state == "已归还") {
          ElMessage.error("该物资已归还，无法更改物资!")
          return
        }
        // 输入新的物资名
        ElMessageBox.prompt('请输入新的物资名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '物资名不能为空'
        }).then(({ value }) => {
          axios.put(`http://localhost:8080/returninfos`,{
            username:row.username,
            itemname:value,
            return_state:0,
            borrow_time:row.borrow_time,
            return_time:null
          })
              .then(res=>{
                if(res.data.status===0){
                  ElMessage.success("更改物资成功!")
                  getData()
                }else{
                  ElMessage.error("更改物资失败!")
                }
              })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消输入'
          });
        });
      })
};
const handleReturnPost = (index: number, row: any) => {
  //TODO 提交归还申请请求
  ElMessageBox.confirm('确定要提交归还申请吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        // 获取当前时间 类型timeStamp
        let return_time = getCurrentDateTime()
        axios.put(`http://localhost:8080/returninfos`,{
          username:row.username,
          itemname:row.itemname,
          return_state:1,
          borrow_time:row.borrow_time,
          return_time:return_time
        })
            .then(res=>{
              if(res.data.status===0){
                ElMessage.success("提交归还申请成功!")
                getData()
              }else{
                ElMessage.error("提交归还申请失败!")
              }
            })
      })
      .catch(() => {});
};
// 删除操作
const handleDelete = (index: number, row: any) => {
  //TODO 注销用户请求
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        axios.delete(`http://localhost:8080/returninfos/`+ row.id)
            .then(res=>{
              if(res.data.status===0){
                ElMessage.success("删除记录成功!")
                getData()
              }else{
                ElMessage.error("删除记录失败!")
              }
            })
      })
      .catch(() => {});
};
function getCurrentDateTime(): string {
  const now = new Date();

  // 获取年、月、日、时、分、秒
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');

  // 拼接成年-月-日-时分秒的形式
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const router = useRouter()
watch(
    () => router.currentRoute.value,
    (newRoute) => {
      if(newRoute.name=="user"){
        getData()
      }
    },
    { immediate: true }
);
</script>

<style scoped>
.handle-box {
  width: auto;
  margin-bottom: 20px;
  display: flex;
  justify-content: left;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #F56C6C;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.temp {
  display: flex;
  justify-content: center;
  width: 80%;
  margin: 0 auto;
}
</style>